package com.halflife.parameter.template;

import com.halflife.framework.converter.MapHandler;
import com.halflife.framework.domain.Page;
import com.halflife.framework.dto.Select2Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class CompanysAdminController {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private CompanysRepository companysRepository;
    @Resource
    private ReturnJsonRepository returnJsonRepository;

    @RequestMapping("/companys/list")
    public String gotoList(@RequestParam(required = false) HashMap<String,Object> queryParam, Page page, HttpServletResponse response,
                           HttpServletRequest request, Model model) {
        MapHandler.handleMap(queryParam);
        if (page == null) {
            page = new Page();
        }
        page.setQueryParam(queryParam);
        queryParam.put("valid", true);
        queryParam.put("orderSql", " t.id asc");
        int totalCount = companysRepository.selectCount(queryParam);
        List<Companys> list = companysRepository.selectListByPage(queryParam);
        page.setTotalCount(totalCount);
        page.setMode(model);
        model.addAttribute("list",list);
        model.addAttribute("queryParam",queryParam);
        return "companys/list";
    }

    @RequestMapping("/companys/operate")
    public String gotoOperate(Long id,HttpServletResponse response,
                               HttpServletRequest request, Model model) {
        Companys companys = new Companys();
        if(id!=null){
            companys = companysRepository.selectByPrimaryKey(id);
        }
        model.addAttribute("companys",companys);
        return "companys/operate";
    }

    @PostMapping("/companys/save")
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity save(Companys companys, HttpServletRequest request,
                              HttpServletResponse response, Model model) {
        try {
            if(companys.getId()!=null){
                companysRepository.updateByPrimaryKey(companys);
            }else {
                companys.init();
                Companys companys1 = companysRepository.selectOne("select max(t.id) as id from t_parameter_company t where t.id<=100000");
                long id = 100000l;
                if (companys1!=null && companys1.getId()!=null) {
                    id = companys1.getId()-1;
                }
                companys.setId(id);
                Integer a = companysRepository.insert(companys);
            }
        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }

    @DeleteMapping("/companys/delete")
    public ResponseEntity delete(Long id, Integer state) {
        try {
            Companys companys = new Companys();
            companys.setId(id);
            companys.setValid(Boolean.FALSE);
            companysRepository.updateByPrimaryKeySelective(companys);
        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }
    private void importCompany(long offset)throws Exception{
        RestTemplate restTemplate = new RestTemplate();
        ReturnJson returnJson = restTemplate.getForObject(new URI("https://api.hubapi.com/companies/v2/companies/paged?hapikey=20eca147-5b6e-4ad4-8bfa-1f54fa43742e&properties=name&limit=250&offset="+offset), ReturnJson.class);
        System.out.println(returnJson.getCompanies().size());
        ReturnJson bo = returnJsonRepository.selectOne("select * from t_parameter_returnjson t where t.offset="+offset);
        if (bo != null) {
            if (bo.getCount() == 250) {
                importCompany(returnJson.getOffset());
                return;
            }else{
                bo.setCount(returnJson.getCompanies().size());
                returnJsonRepository.updateByPrimaryKeySelective(bo);
            }
        }
        for (CompanyJson companyJson : returnJson.getCompanies()) {
            Companys companys = companysRepository.selectByPrimaryKey(companyJson.getCompanyId());
            if (companys == null) {
                companys = new Companys(companyJson);
                companysRepository.insert(companys);
            }

        }
        if (returnJson.getHasMore()) {
            importCompany(returnJson.getOffset());
        }

    }
    @GetMapping("/companys/import")
    public ResponseEntity importCompanys() {
        try {
           importCompany(0);

        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }

    @GetMapping("/companys/json")
    public ResponseEntity getJson(String search,Integer page) {
        Select2Json<Companys> select2Json = new Select2Json();
        try {
            Page pg = new Page();
            pg.setPageNo(page);
            Map queryParam = new HashMap();
            pg.setQueryParam(queryParam);
            queryParam.put("name", search);
            int totalCount = companysRepository.selectCount(queryParam);
            List<Companys> list = companysRepository.selectListByPage(queryParam);
            pg.setTotalCount(totalCount);

            select2Json.setResults(list);
            if (pg.getTotalPage() == page) {
                select2Json.getPagination().setMore(false);
            } else {
                select2Json.getPagination().setMore(true);
            }
        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(select2Json, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(select2Json, HttpStatus.OK);
    }
}
